<template>
  <div class="container">
    <el-row>
      <el-col class="top-search">
        <el-input
          :value="listQuery.memberId"
          :maxlength="MaxMemberIdLength"
          :placeholder="$t('please_input_member_id')"
          clearable
          class="w-180"
          @input="
            (value) => (listQuery.memberId = value.replace(/[^\d]/g, ''))
          "/>
        <el-input v-model="listQuery.nickName" :placeholder="$t('please_enter_member_nickname')" clearable class="w-240"/>
        <el-input
          :value="listQuery.mobile"
          :placeholder="$t('please_input_mobile_phone_number')"
          clearable
          class="w-180"
          @input="
            (value) => (listQuery.mobile = value.replace(/[^\d]/g, ''))
          "/>
        <label for="">{{ $t('applied_time') }}:</label>
        <el-date-picker
          v-model="datePicker1"
          class="w-240"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd"
        />
        <label for="">{{ $t('processing_time') }}:</label>
        <el-date-picker
          v-model="datePicker2"
          class="w-240"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd"
        />
        <el-button type="primary" @click="search"> {{ $t('search') }} </el-button>
      </el-col>

      <el-col class="p-t-15">
        <el-menu
          :default-active="listQuery.status"
          class="el-menu-demo"
          mode="horizontal"
          @select="switchTab"
        >
          <el-menu-item index="0">{{ $t('not_yet_process') }}</el-menu-item>
          <el-menu-item index="1">{{ $t('approved') }}</el-menu-item>
          <el-menu-item index="-1">{{ $t('not_approved') }}</el-menu-item>
        </el-menu>
      </el-col>

      <el-col class="p-t-20">
        <el-table
          v-loading="listLoading"
          :data="listData"
          border
          fit
          highlight-current-row
        >
          <el-table-column :label="$t('serial_number')" width="60" align="center">
            <template slot-scope="scope">
              <span>
                {{ (listQuery.page - 1) * listQuery.size + scope.$index +1 }}
              </span>
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('member_id')"
            prop="memberId"
            align="center"
            width="120"
          />
          <el-table-column
            :label="$t('member_nickname')"
            prop="nickName"
            align="center"
          />
          <el-table-column
            :label="$t('phone_number')"
            prop="mobile"
            align="center"
            width="120"
          />
          <el-table-column
            :label="$t('applied_time')"
            prop="applyTime"
            align="center"
          />
          <el-table-column
            :label="$t('application_details')"
            align="center"
            width="120"
          >
            <template slot-scope="{row}">
              <el-button type="primary" @click="applyDetail(row.id, row.memberId)"> {{ $t('details') }} </el-button>
            </template>
          </el-table-column>

          <el-table-column
            v-if="listQuery.status!=0"
            :label="$t('processing_time')"
            prop="handleTime"
            align="center"
          />
          <el-table-column
            :label="$t('member_status_change_times')"
            align="center"
            width="210"
          >
            <template slot-scope="{row}">
              <el-button :disabled="row.updateNum==0" type="primary" @click="checkHistory(row.memberId)"> {{ row.updateNum }} </el-button>
            </template>
          </el-table-column>

          <el-table-column :label="$t('operation')" align="center" width="420">
            <template slot-scope="{row}">
              <el-button
                v-if="listQuery.status==0"
                type="primary"
                @click="handle(row, 1)"
              >
                {{ $t('pass') }}
              </el-button>

              <el-button
                v-if="listQuery.status==0"
                type="danger"
                @click="handle(row, -1)"
              >
                {{ $t('audit_reject') }}
              </el-button>

              <el-button
                type="primary"
                @click="goDetail(row.memberId)"
              >
                {{ $t('member_details') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="total > 0" class="block fr p-t-20">
          <el-pagination
            :current-page="listQuery.page"
            :page-sizes="[15, 20, 30]"
            :page-size="listQuery.size"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="(val) => handlePageChange(val, 'size')"
            @current-change="(val) => handlePageChange(val, 'page')"
          />
        </div>
      </el-col>
    </el-row>

    <!-- 状态变更次数 -->
    <state-change-history :show.sync="show.history" :listData="historyData" />

    <!-- 申请详情 -->
    <el-dialog :visible.sync="show.details" :title="$t('unusual_change_application_detail')" append-to-body width="800px">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item :label="$t('member_status') + ':'">
          <span>{{ riskStatusMap[form.riskStatus] }}</span>
        </el-form-item>
        <el-form-item :label="$t('elimination_reason')+ ':'">
          <el-input v-model="form.relieveReason" type="textarea" autosize />
        </el-form-item>
        <el-form-item :label="$t('name')+ ':'">
          <span>{{ form.name }}</span>
        </el-form-item>
        <el-form-item :label="$t('id_type')+ ':'">
          <span>{{ certTypeMap[form.certType] }}</span>
        </el-form-item>
        <el-form-item :label="$t('id_no')+ ':'">
          <span>{{ form.certNum }}</span>
        </el-form-item>
        <el-form-item :label="$t('certificate_photo')+ ':'">
          <el-image v-for="(url, index) in form.certPhoto" :key="index" :src="url" :preview-src-list="form.certPhoto" class="details-img"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show.details = false;">{{ $t('close') }}</el-button>
      </span>
    </el-dialog>

    <!-- 处理 -->
    <el-dialog :visible.sync="show.handle" :title="$t('process_of_unusual_status_elimination_application')" width="800px">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item :label="$t('application_in_processing')">
          <el-radio-group v-model="form.status" @change="form.changeReason=null">
            <el-radio :label="1">{{ $t('pass') }}</el-radio>
            <el-radio :label="-1">{{ $t('audit_reject') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="form.status==1" >
          <el-form-item :label="$t('status_change')">
            <span>{{ $t('change_to_normal') }}</span>
          </el-form-item>
          <el-form-item :label="$t('change_type')">
            <el-select
              :placeholder="$t('please_select')"
              v-model="form.changeType"
              class="w-400"
            >
              <el-option :value="1" :label="$t('recovery_system_abnormal')"/>
              <el-option :value="2" :label="$t('recovery_human_being_error')"/>
              <el-option :value="3" :label="$t('recovery_other_causes')"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('change_reason')">
            <el-input v-model="form.changeReason" :placeholder="$t('words_5_1000')" :rows="5" type="textarea" maxlength="1000" />
          </el-form-item>
        </div>
        <el-form-item v-if="form.status==-1" :label="$t('reasons_for_refusal')">
          <el-input v-model="form.changeReason" :placeholder="$tt('within_MAX_words_the_reason_for_rejection_will_be_sent_to_the_user_via_sms', { MAX: 300 })" :rows="5" type="textarea" maxlength="300" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show.handle = false;">{{ $t('close') }}</el-button>
        <el-button :loading="btnLoading" :disabled="btnLoading" type="primary" @click="confirmHandle">{{ $t('confirm') }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getMemberriskApplyListApi, getApplyDetailsApi, getChangeRecordsApi, updateStatusApi } from '@/api/user-exception-filtering/releaseProcessing.js';
import StateChangeHistory from '@/views/member-exception-filtering//components/StateChangeHistory.vue';

const MaxMemberIdLength = 18;

export default {
  components: {
    StateChangeHistory
  },

  data() {
    return {
      MaxMemberIdLength,
      datePicker1: [],
      datePicker2: [],
      listLoading: false,
      btnLoading: false,
      listQuery: {
        memberId: null,
        nickName: null,
        mobile: null,
        status: '0', // 0-未处理 1-已通过 -1-不通过
        applyBeginTime: null,
        applyEndTime: null,
        handleBeginTime: null,
        handleEndTime: null,
        page: 1,
        size: 15,
        lan: 'zh-Hans'
      },
      listData: [],
      historyData: [],
      total: 0,
      show: {
        history: false,
        details: false,
        handle: false
      },
      form: {
        fuck: null
      },
      riskStatusMap: {
        1: this.$t('normal'),
        2: this.$t('suspicious_situation'),
        3: this.$t('grey_list'),
        4: this.$t('black_list')
      },
      certTypeMap: {
        1: this.$t('id_card'),
        2: this.$t('student_id_card'),
        3: this.$t('passport')
      },
      statusMap: {
        GREY: this.$t('grey_list'),
        BLACK: this.$t('black_list'),
        NORMAL: this.$t('normal'),
        NOTSURE: this.$t('suspicious_situation'),
        WHITE: this.$t('white_list'),
        GREYANDBLACK: this.$t('blacklist_or_grey_list')
      }
    };
  },

  created() {
    const lan = this.$store.state.app.language || 'zh';
    const lanMap = {
      'zh': 'zh-Hans',
      'en': 'en-US',
      'km': 'km-KH'
    };
    this.listQuery.lan = lanMap[lan];
    this.search();
  },

  methods: {
    search() {
      let { applyBeginTime, applyEndTime, handleBeginTime, handleEndTime } = this.listQuery;
      const { datePicker1, datePicker2 } = this;
      applyBeginTime = datePicker1 && datePicker1[0] ? datePicker1[0] + ' 00:00:00' : null;
      applyEndTime = datePicker1 && datePicker1[1] ? datePicker1[1] + ' 23:59:59' : null;
      handleBeginTime = datePicker2 && datePicker2[0] ? datePicker2[0] + ' 00:00:00' : null;
      handleEndTime = datePicker2 && datePicker2[1] ? datePicker2[1] + ' 23:59:59' : null;

      this.listQuery = { ...this.listQuery, applyBeginTime, applyEndTime, handleBeginTime, handleEndTime, page: 1 };
      this.getList();
    },

    async getList() {
      if (this.listLoading) return;
      this.listLoading = true;

      try {
        const { code, data, msg } = await getMemberriskApplyListApi(this.listQuery);
        this.listLoading = false;
        if (code == 200) {
          this.listData = data.result || [];
          this.total = Number(data.count) || 0;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.listLoading = false;
      }
    },

    formatForShow() {
      const { certPhoto } = this.form;
      this.form.certPhoto = certPhoto ? certPhoto.split(';') : [];
    },

    async applyDetail(applyId, memberId) {
      try {
        const { code, data, msg } = await getApplyDetailsApi({ applyId, memberId });
        if (code == 200) {
          this.form = data || {};
          this.formatForShow();
          this.show.details = true;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.$message.warning(this.$t('there_was_an_error_in_the_request'));
      }
    },

    async checkHistory(memberId) {
      try {
        const { code, data, msg } = await getChangeRecordsApi({ memberId });
        if (code == 200) {
          this.historyData = this.formatRule(
            JSON.parse(JSON.stringify(data || []))
          );
          this.show.history = true;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.$message.warning(this.$t('there_was_an_error_in_the_request'));
      }
    },

    // 规则格式化
    formatRule(data) {
      const rule = data.map(item => {
        item.firstRuleGroupName = '';
        item.allRules = '';
        const rule = item.ruleGroupNameList;
        rule.forEach((ruleItem, index) => {
          if (
            !ruleItem.frequency && !ruleItem.operator && !ruleItem.periodOfTime
          ) {
            if (index == 0) {
              item.firstRuleGroupName = ruleItem.ruleName;
            } else {
              ruleItem.ruleName = ruleItem.ruleName + ';';
            }
            item.allRules += ruleItem.ruleName;
          } else {
            let all = '';
            if (ruleItem.operator == '') {
              all = `${ruleItem.ruleName} ${ruleItem.periodOfTime}${
                ruleItem.frequency
              }`;
            } else {
              all = `${ruleItem.ruleName} ${ruleItem.periodOfTime}${
                ruleItem.frequency
              }${ruleItem.operator}${ruleItem.value}`;
            }

            if (index == 0) {
              item.firstRuleGroupName = all;
            }
            item.allRules += `${all} ; `;
          }
        });
        return item;
      });
      return rule;
    },

    switchTab(val) {
      this.listQuery.status = val;
      this.listQuery.page = 1;
      this.getList();
    },

    handle({ id, memberId }, status) {
      this.form = {
        id,
        memberId,
        status,
        afterStatus: 1,
        changeType: 3,
        changeReason: null
      };
      this.show.handle = true;
    },

    async confirmHandle() {
      const { id, memberId, status, changeType, changeReason } = this.form;
      if (status == 1 && (!changeReason || changeReason.length < 5)) {
        this.$message.warning(this.$t('the_word_number_range_of_reason_for_change_is_5_1000'));
        return;
      }

      if (status == -1 && !changeReason) {
        this.$message.warning(this.$t('please_fill_in_the_rejection_reason_and_send_the_sms_to_the_user'));
        return;
      }

      const query = { id, memberId, status, changeType, changeReason, afterStatus: status };
      this.btnLoading = true;

      try {
        const { state, error_msg } = await updateStatusApi(query);
        this.btnLoading = false;
        if (state == 1) {
          this.$message.success(this.$t('operation_successful'));
          this.show.handle = false;
          this.getList();
        } else {
          this.$message.warning(error_msg);
        }
      } catch (e) {
        this.btnLoading = false;
      }
    },

    goDetail(memberId) {
      const url = `${process.env.DATA_ADMIN}/#/userExceptionFilter/userDetail?memberId=${memberId}`;
      window.open(url);
    },

    handlePageChange(val, name) {
      this.listQuery[name] = val;
      this.getList();
    }
  }
};
</script>

<style lang="scss" scoped>
 .details-img {
    display: inline-block;
    width: 298px;
    height: 224px;
    object-fit: cover;
    margin: 0 20px 20px 0;
  }
</style>
